package com.company.wechatpush.controller;

import com.company.wechatpush.service.TokenService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @author Real
 * Date: 2022/9/3 4:00
 */
@RestController
public class TokenController {

    @RequestMapping("/wx")
    public String handle() {
        return "hello, this is handle view.";
    }

    /**
     * 微信公众平台中设置的token
     */
    public static final String Token = "123456";

    @RequestMapping("/")
    public void index(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String method = request.getMethod();
        if ("GET".equals(method)) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            String[] str = {Token, timestamp, nonce};
            // 字典排序
            Arrays.sort(str);
            String bigStr = str[0] + str[1] + str[2];
            // SHA1加密
            String digest = TokenService.sha1(bigStr);
            // 确认请求来至微信
            if (digest.equals(signature)) {
                response.getWriter().print(echostr);
            }
        }
    }


}
